<template>
  <div class="channel-edit">
    <!-- 当前登陆用户已经订阅的频道 -->
    <div class="channel">
      <van-cell title="我的频道" :border="false">
        <van-button size="mini" type="info" @click="edit">{{clickEdit?"取消":"编辑"}}</van-button>
      </van-cell>
      <van-grid>
        <van-grid-item v-for="(item,index) in channeldata" :key="index">
          <span @click="choseChannel(index)">{{item.name}}</span>
          <van-icon name="cross" class="btn" v-show="clickEdit&&index!=0" @click="delChannel(index)"></van-icon>
        </van-grid-item>
      </van-grid>
    </div>
    <!-- 当前登陆用户没有订阅的频道 -->
    <div class="channel">
      <van-cell title="可选频道" :border="false"></van-cell>
      <van-grid>
        <van-grid-item v-for="(item,index) in optionalChannel" :key="index" @click.stop="addMyChannel(item)">
          <span>{{ item.name}}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>
<script>
import { getAllChannels } from '@/api/channel'
import { setItem } from '@/utils/ls'
export default {
  props: {
    channeldata: {
      type: Array
    }
  },
  data () {
    return {
      clickEdit: false, // 编辑切换状态
      allChannelList: []// 所以数据信息
    }
  },
  computed: {
    optionalChannel () {
      return this.allChannelList.filter((value) => {
        const index = this.channeldata.findIndex((channel) => {
          return value.id === channel.id
        })
        if (index === -1) {
          return value
        }
      })
    }
  },
  mounted () {
    this.loadChannelList()
  },
  methods: {
    // 编辑切换状态
    edit () {
      this.clickEdit = !this.clickEdit
    },
    // 渲染页面
    loadChannelList () {
      // 调用接口
      getAllChannels().then((res) => {
        console.log(res)
        this.allChannelList = res.data.data.channels
      }).catch((err) => {
        console.log(err)
      })
    },
    // 选择该频道
    choseChannel (index) {
      this.$emit('choseChannelNow', index)
    },
    // 删除该频道
    delChannel (index) {
      console.log('点击了删除', index)
      // 向父级发出一个点击信息及所需信息
      this.$emit('delChannelData', index)
      // 将数据存到本地内
      setItem('addMy', this.channeldata)
      this.$toast.success('取消成功啦')
    },
    // 添加到我的频道
    addMyChannel (index) {
      // 在数组里添加新的数据
      this.channeldata.push(index)
      // 保存到本地
      setItem('addMy', this.channeldata)
      this.$toast.success('添加成功啦')
    }
  }

}
</script>
<style lang="less" scoped>
.channel {
  font-size: 13px;
}
.btn {
  position: absolute;
  top: 2px;
  right: 2px;
  font-size: 14px;
  color:red;
}
</style>
